package com.woniuedu.search.direct;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.woniuedu.search.entity.MessageStatusEnum;
import com.woniuedu.search.entity.Messages;
import com.woniuedu.search.mapper.MessageMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;


@Slf4j
@Component
public class RabbitMQConfirm implements RabbitTemplate.ConfirmCallback {



    @Autowired(required = false)
    private MessageMapper messageMapper;

    @Resource
    private KillSender killSender;

    /**
     * confirm模式回调函数
     *
     * @param correlationData 消息信息
     * @param ack             确认标记;true:exchange收到消息;false没有收到消息
     * @param cause           没有收到消息的原因;如果收到消息输出null
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        String correlationDataId = correlationData.getId();
        if (ack) {
            //ACK
            log.debug("消息[{}]投递成功，将DB中的消息状态设置为投递成功", correlationDataId);
            messageMapper.update(null,
                    Wrappers.<Messages>lambdaUpdate()
                            .set(com.woniuedu.search.entity.Messages::getStatus, MessageStatusEnum.SUCCESS.getStatus())
                            .eq(com.woniuedu.search.entity.Messages::getId, correlationDataId)
            );
        } else {
            log.debug("消息[{}]投递失败,cause:{}", correlationDataId, cause);
            //NACK，消息重发
            killSender.reSend(correlationData.getId());
        }
    }

}
